package com.rzn.reading.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class CopyToOtherUtil<S, T> {
    private S source;
    private T target;

    public CopyToOtherUtil(S source, T target) {
        this.source = source;
        this.target = target;
    }

    public S getSource() {
        return source;
    }

    public void setSource(S source) {
        this.source = source;
    }

    public T getTarget() {
        return target;
    }

    public void setTarget(T target) {
        this.target = target;
    }

    /**
     * 将源对象的值复制到目标对象中
     *
     * @return
     * @Author 86176
     * @Create 2021/12/22 10:33
     */
    public void translate() {
        Class<?> entityClass = source.getClass();
        Class<?> targetClass = target.getClass();
        Field[] entityFields = entityClass.getDeclaredFields();
        for (Field entityField : entityFields) {
            String fieldName = entityField.getName();
            fieldName = StringUtil.toTitle(fieldName);

            try {
                Method entityMethod = entityClass.getMethod("get" + fieldName);
                Method targetMethod = targetClass.getMethod("set" + fieldName, entityField.getType());
                Object value = entityMethod.invoke(source);
                targetMethod.invoke(target, value);
            } catch (NoSuchMethodException e) {
                System.out.println("方法" + "'" + e.getMessage() + "'" + "没找到");
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
}
